using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Newtonsoft.Json;
using XamarinApp.Droid.Models;

namespace XamarinApp.Droid.Services
{
	public class WebService
	{
		public async Task<List<ListItemModel>> FetchLatestPosts(string url = "http://engismo.com/api/get_recent_posts/")
		{
			HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
			webRequest.ContentType = "application/json";
			webRequest.Method = "GET";

			List<ListItemModel> finalResult = new List<ListItemModel>();
			using (WebResponse response = await webRequest.GetResponseAsync())
			{
				using (StreamReader reader = new StreamReader(response.GetResponseStream()))
				{
					
					var content = reader.ReadToEnd();
					if (string.IsNullOrWhiteSpace(content))
						return finalResult;
					
					ApiModel result = JsonConvert.DeserializeObject<ApiModel>(content);
					finalResult.AddRange(result.posts.Select(item => new ListItemModel()
					{
						Id = item.id,
						Title = WebUtility.HtmlDecode(item.title),
						Excerpt = WebUtility.HtmlDecode(item.excerpt),
						Content = WebUtility.HtmlDecode(item.content),
						FeaturedImage = item.thumbnail
					}));
				}
			}

			return finalResult;
		}
	}
}